package com.heima.article.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.heima.article.dto.*;
import com.heima.article.entity.*;
import com.heima.article.feign.BehaviorFeign;
import com.heima.article.feign.UserFeign;
import com.heima.article.mapper.ApArticleMapper;
import com.heima.article.service.*;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.dto.ResponseResult;
import com.heima.common.dto.User;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.common.util.MediaThreadLocalUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.lang.reflect.InvocationTargetException;
import java.security.Key;
import java.util.*;

/**
 * <p>
 * 文章信息表，存储已发布的文章 服务实现类
 * </p>
 *
 * @author mcm
 * @since 2022-06-23
 */
@Service
public class ApArticleServiceImpl extends ServiceImpl<ApArticleMapper, ApArticle> implements IApArticleService {

    @Autowired
    IApArticleContentService apArticleContentService;

    @Autowired
    private ITemplateService templateService;
    @Override
    public ResponseResult<Long> saveArticle(ArticleDto dto) {
        //创建文章表
        ApArticle article=new ApArticle();
        //属性拷贝
        BeanUtils.copyProperties(dto,article);
        //如果不存在文章id
        if (dto.getId()==null){
            article.setCreatedTime(new Date());
            article.setPublishTime(new Date());
            //新增文章
            this.save(article);
            //保存内容
            String content = dto.getContent();
            //新建文章内容表
            ApArticleContent articleContent=new ApArticleContent();
            articleContent.setArticleId(article.getId());
            articleContent.setContent(content);
            //保存文章内容
            apArticleContentService.save(articleContent);

            //生成html静态页面,需要异步处理

            System.out.println(Thread.currentThread().getName()+"开始调用生成静态html服务...");
            templateService.createHtml(article,dto.getContent());
            System.out.println(Thread.currentThread().getName() + " 生成静态html调用结束");
            //返回
            return ResponseResult.okResult(article.getId());
        }else {
            //如果不存在,更新文章
            this.updateById(article);
            //保存文章内容
            LambdaUpdateWrapper<ApArticleContent> query = new LambdaUpdateWrapper<>();
            //根据文章id
            query.eq(ApArticleContent::getArticleId,dto.getId());
            //修改文章内容
            query.set(ApArticleContent::getContent,dto.getContent());
            apArticleContentService.update(query);

            //更新url静态地址
            System.out.println(Thread.currentThread().getName() + " 开始更新调用生成静态html服务...");
                article.setStaticUrl(null);
            templateService.createHtml(article,dto.getContent());
            System.out.println(Thread.currentThread().getName() + " 更新调用生成静态html服务完成...");
            //返回
            return ResponseResult.okResult(dto.getId());
        }
    }

    @Autowired
    private StringRedisTemplate redisTemplate;
    /**
     * 加载文章列表
     * @param dto
     * @param type
     * @return
     */
    @Override
    public ResponseResult loadArticle(ArticleHomeDto dto, int type) {
        //判断是否是首页加载数据,如果是先从redis中查询
        if (dto.getLoaddir()==1){
            //先从redis中查询数据,按照分值从大到小排序
           String Key="hot_article_"+dto.getChannelId();
           long start=0;
           long end=dto.getSize()-1;
            Set<String> strings = redisTemplate.opsForZSet().reverseRange(Key, start, end);
            List<ApArticle> articles = new ArrayList<>();
            for (String string : strings) {
                ApArticle article = JSON.parseObject(string, ApArticle.class);
                articles.add(article);
            }
            if (articles.size()==dto.getSize()){
                return ResponseResult.okResult(articles);
            }
        }
        // 分页查询
        LambdaQueryWrapper<ApArticle> query = new LambdaQueryWrapper<>();
        // 判断频道
        if (dto.getChannelId() != 0) {
            query.eq(ApArticle::getChannelId, dto.getChannelId());
        }
        // 如果是已下架或者标明已删除的文章则不被查询出来
        query.eq(ApArticle::getIsDelete, false);
        query.eq(ApArticle::getIsDown, false);
        if (type == 0) {
            // 如果是加载更多,查询比前端传递的最小时间还早的文章
            query.lt(ApArticle::getPublishTime, dto.getMinTime());
        } else {
            // 如果是加载最新,查询比前端传递的最大时间还晚的文章
            query.gt(ApArticle::getPublishTime, dto.getMaxTime());
        }
        // 按照发布时间倒序排
        query.orderByDesc(ApArticle::getPublishTime);
        IPage<ApArticle> page = new Page<>(1, dto.getSize());

        IPage<ApArticle> iPage = this.page(page, query);
        // 只需要给前端返回数据
        return ResponseResult.okResult(iPage.getRecords());
    }
    /**
     * 文章详情
     * @param dto
     * @return
     */
    @Override
    public ResponseResult loadArticleInfo(ArticleInfoDto dto) {
        //根据id查询文章对象
        ApArticle byId = this.getById(dto.getArticleId());
        //构建查询条件
        LambdaQueryWrapper<ApArticleContent> query = new LambdaQueryWrapper<>();
        //根据id查询文章内容
        query.eq(ApArticleContent::getArticleId,dto.getArticleId());
        ApArticleContent one = apArticleContentService.getOne(query);
        HashMap<String, Object> map = new HashMap<>();
        //文章内容
        map.put("config",byId);
        //文字内容
        map.put("content",one);
        return ResponseResult.okResult(map);

    }

    @Autowired
    private IApCollectionService collectionService;
    /**
     * 收藏行为
     * @param dto
     * @return
     */
    @Override
    public ResponseResult collect(CollectionBehaviorDto dto) {
        User user = MediaThreadLocalUtil.get();
        if(user==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        //构建收藏记录
        ApCollection apCollection=new ApCollection();
        apCollection.setEntryId(user.getUserId());
        apCollection.setArticleId(dto.getArticleId());
        apCollection.setCollectionTime(new Date());

        //判断是否收藏
        LambdaQueryWrapper<ApCollection> query = new LambdaQueryWrapper<>();
        //根据文章id查询
        query.eq(ApCollection::getArticleId,dto.getArticleId());
        //根据用户id查询
//        query.eq(ApCollection::getEntryId,dto.getEquipmentId());
        ApCollection one = collectionService.getOne(query);
        //如果不存在,新增
        if (one==null) {
            if (dto.getOperation() == 0) {
                collectionService.save(apCollection);
                sendMessage(dto);
            }
        }else {
            //如果存在,删除
            if (dto.getOperation()==1){
                collectionService.removeById(dto.getArticleId());
                sendMessage(dto);
            }
        }
        return ResponseResult.okResult();
    }

    @Autowired
    private KafkaTemplate<String,String> kafkaTemplate;

    @Value("${topic.collect_behavior}")
    private String collect;
    /**
     * 发信息到kafka
     * @param dto
     */
    private void sendMessage(CollectionBehaviorDto dto) {
        UpdateArticleMessage message=new UpdateArticleMessage();
        message.setType(3);
        message.setArticleId(dto.getArticleId());
        message.setAdd(1);
        if (dto.getOperation()==1){
            message.setAdd(-1);
        }
        String value = JSON.toJSONString(message);
        kafkaTemplate.send(collect,value);
    }

    @Autowired
    private BehaviorFeign behaviorFeign;

    @Autowired
    private UserFeign userFeign;

    @Autowired
    private IApAuthorService authorService;
    /**
     * 加载文章记录行为
     * @param dto
     * @return
     */
    @Override
    public ResponseResult loadArticleBehavior(ArticleInfoDto dto) {
        boolean isFollow = false;
        boolean isCollection = false;
        boolean isLike = false;
        boolean isUnlike = false;

        User user = MediaThreadLocalUtil.get();

        // 查询点赞记录
        LikesBehaviorDto likeDto = new LikesBehaviorDto();
        likeDto.setEquipmentId(dto.getEquipmentId());
        if (user != null) {
            likeDto.setUserId(user.getUserId());
        }
        likeDto.setArticleId(dto.getArticleId());
        ResponseResult<ApLikesBehavior> likesBehaviorResponseResult = behaviorFeign.getLikes(likeDto);
        if (likesBehaviorResponseResult.getCode().equals(AppHttpCodeEnum.SUCCESS.getCode())) {
            ApLikesBehavior likesBehavior = likesBehaviorResponseResult.getData();
            if (likesBehavior != null && likesBehavior.getOperation() == 0) {
                isLike = true;
            }
        }

        //查询不喜欢记录
        UnLikesBehaviorDto unLikesBehaviorDto = new UnLikesBehaviorDto();
        BeanUtils.copyProperties(likeDto,unLikesBehaviorDto);
        ResponseResult<ApUnlikesBehavior> unlikes = behaviorFeign.getUnlikes(unLikesBehaviorDto);
        if (unlikes.getCode().equals(AppHttpCodeEnum.SUCCESS.getCode())){
            ApUnlikesBehavior data = unlikes.getData();
            if (data!=null && data.getType()==0){
                isUnlike=true;
            }
        }

        //查询收藏记录
        if (user!=null){
            LambdaQueryWrapper<ApCollection> query = new LambdaQueryWrapper<>();
            query.eq(ApCollection::getEntryId,user.getUserId());
            query.eq(ApCollection::getArticleId,dto.getArticleId());
            ApCollection one = collectionService.getOne(query);
            if (one !=null){
                isCollection=true;
            }
        }
        //查询关注记录
        if (user!=null){
            FollowBehaviorDto followBehaviorDto = new FollowBehaviorDto();
            followBehaviorDto.setUserId(user.getUserId());
            ApAuthor author = authorService.getById(dto.getAuthorId());
            followBehaviorDto.setFollowId(author.getUserId());
            ResponseResult<ApUserFollow> follow = userFeign.getFollow(followBehaviorDto);
            if (follow.getCode().equals(AppHttpCodeEnum.SUCCESS.getCode())){
                ApUserFollow data = follow.getData();
                if (data!=null){
                    isFollow=true;
                }
            }
        }
        //返回给前端固定的格式
        HashMap<String, Boolean> map = new HashMap<>();
        map.put("isfollow", isFollow);
        map.put("islike", isLike);
        map.put("isunlike", isUnlike);
        map.put("iscollection", isCollection);
        return ResponseResult.okResult(map);
    }
}
